package com.black.gateway.auth.controller;

import com.black.gateway.auth.service.AuthService;
import com.black.gateway.auth.vo.AuthToken;
import com.black.gateway.auth.vo.TokenRequestVo;
import com.black.gateway.exception.OauthException;
import com.black.gateway.web.ApiResponse;
import com.black.gateway.web.ApiResponseBuilder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author linwenfeng
 */
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginController {

    private final AuthService authService;

    @PostMapping("system/login")
    public ApiResponse<AuthToken> login(@RequestBody Map<String, String> parameters) {
        return ApiResponseBuilder.ok(authService.login(parameters.get("username"), parameters.get("password")));
    }

    @PostMapping("system/token")
    public ApiResponse<AuthToken> token(@RequestBody TokenRequestVo requestVo) {
        return ApiResponseBuilder.ok(authService.getUserToken(requestVo.getCode(), requestVo.getClientId()));
    }

    @ExceptionHandler(OauthException.class)
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED)
    public ApiResponse<String> oauthExceptionHandler(OauthException exception) {
        return ApiResponseBuilder.wrap(HttpStatus.UNAUTHORIZED.value(), exception.getMessage());
    }

}
